home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: malloc question
- Date: 10 Mar 1996 10:08:25 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4hv5qpINNp8a@keats.ugrad.cs.ubc.ca>
- References: <4htonk$350@news.hklink.net> <4huctt$arv@sparcserver.lrz-muenchen.de>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4huctt$arv@sparcserver.lrz-muenchen.de>,
- Kurt Watzka <watzka@stat.uni-muenchen.de> wrote:
- >alex@station.net (Alex Chu) writes:
- >
- >
- >>Hi everybody,
- >
- >>I have a question for the following snip C program.
- >
- >>typedef struct item {
- >> int val;
- >> struct item *next;
- >>} ITEM, *PITEM;
- >
- >>main()
- >>{
- >> PITEM head, current;
- >> head=(PITEM) malloc(sizeof(ITEM));
- >> ^^^^^^^
- >> head->val=1;
- >>}
- >
- >>I want to know why need to use the type casting PITEM in front of the
- >>malloc ? Please help!
- >
- >Simple answer: You don't have to use that cast, and you should _not_ use
- >it, because all you can do with that cast is _hide_ an error.
-
- That is true. In fact, in this case there is an error that has been hidden.
-
- A use of malloc() requires that the <stdlib.h> header be included. Otherwise,
- the compiler will assume the default declaration: ``int malloc();''.
-
- The cast in this case does indeed hide an error, because it coerces an int type
- into a pointer.
-
- The declaration for malloc() gives it a void * return type, which can, in this
- case, be converted to any pointer type (only because malloc() ensures that it
- can meet the strictest alignment requirements)
-
- assignment-compatible with any pointer.
-
- >OTOH, if you are using a C++ compiler to translate C programs, the cast
- >is needed, but malloc() is obsolete.
-
- That is completely false. It is the only standard defined way to allocate
- memory. When C++ becomes standardized, malloc() can be considered obsolete and
- only from the point of view of C++. It is, however, an integrated, standardized
- part of the _C_ language. A C compiler is free to treat it, and other defined
- functions, as a special operator for the purposes of optimizing a call to
- malloc(), unless it has already encountered a static declaration of the malloc
- identifier in the scope where the call occurs---malloc() is no mere external
- function, it is a special language feature painstakingly dressed up to look
- like a library function, even to the point that you can take the address of
- malloc() and call it via a function pointer.
- --
-
-